import { _decorator, Component, error, Node, random, sys } from 'cc';
import { platform } from './platform';
import { GameData, SecondaryGunStruct } from '../system/GameData';
import { AppControll, ConfigKey, EventName } from '../manager/AppControll';
import { DataHelper } from '../system/DataHelper';
import EvtManger from '../tools/EvtManger';
const { ccclass, property } = _decorator;

@ccclass('platform_Wx')
export class platform_Wx extends platform {
    private strBannerId = "";
    
    private strRewardVideoId = "adunit-a604a22b0e6b737c";
    private strMateId = "adunit-2ccfac14c1a171e6";
    private strInterstitialId = "adunit-1bc215f18d63a50a"

    private database: any = null;
    private userInfo: any = null;
    private clubBtn: any = null;
    private innerAudioContext = null;
    constructor() {
        super();
        if (sys.platform != sys.Platform.WECHAT_GAME) {
            console.log("当前环境不是微信小程序")
            return;
        }

        this.Login();
        this.InitInnerAudioContext();
        this.InitRewardVideoAd();
        this.InitInterstitialAd();
        this.InitShare();
        this.InitDataBase();
        this.GetOpenId();
    }

    InitInnerAudioContext() {
        this.innerAudioContext = wx.createInnerAudioContext();

        //以下监听事件只需要注册一次就行
        this.innerAudioContext.onPlay(() => {//监听播放事件
            console.log("onPlay");
        })
        this.innerAudioContext.onStop(() => {//监听停止事件
            console.log("onStop");
        })
        this.innerAudioContext.onPause(() => {//监听暂停事件
            console.log("onPause");
        })
    }

    Login() {
        let self = this;
        wx.login().then((temp) => {
            wx.getSetting({
                success(res) {
                    if (res.authSetting["scope.userInfo"]) {
                        wx.getUserInfo({
                            success: function (res) {
                                self.userInfo = res.userInfo;
                                GameData.userInfo = res.userInfo;
                                AppControll.Platform.UpdateRank();
                            },
                            fail: function (err) {
                            }
                        })
                    } else {
                        wx.getUserProfile({
                            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
                            success: (res) => {
                                self.userInfo = res.userInfo;
                                GameData.userInfo = res.userInfo;
                                AppControll.Platform.UpdateRank();
                            },
                            fail: (res) => {
                                AppControll.Platform.UpdateRank();
                            }
                        })
                    }
                }
            })
        })
    }

    InitInterstitialAd() {
        if (sys.platform != sys.Platform.WECHAT_GAME) {
            console.log("当前环境不是微信小程序")
            return;
        }
        this.adInterstitial = wx.createInterstitialAd({ adUnitId: this.strInterstitialId })
        this.adInterstitial.onLoad(() => {
            console.log('插屏 广告加载成功')
        })

        this.adInterstitial.onClose(res => {
            AppControll.ShelvedTime = 0;
            AppControll.IsShowInitInterstitial = false;
        })

        this.adInterstitial.onError(err => {
            setTimeout(() => {
                this.adInterstitial = wx.createInterstitialAd({ adUnitId: this.strInterstitialId });
            }, 0.5);
        })
    }

    InitRewardVideoAd() {
        if (sys.platform != sys.Platform.WECHAT_GAME) {
            console.log("当前环境不是微信小程序")
            return;
        }
        this.adVideoAd = wx.createRewardedVideoAd({ adUnitId: this.strRewardVideoId });
        this.adVideoAd.onLoad(() => {
            console.log('激励视频 广告加载成功')
        })

        this.adVideoAd.onError(err => {
            console.error(err)
        })

        this.adVideoAd.onClose(res => {
            if (res && res.isEnded || res === undefined) {
                if (this.callBack) {
                    this.callBack(true, "")
                    this.callBack = null;
                }
            }
            else {
                console.log("播放失败 0")
                // 播放中途退出，不下发游戏奖励
                if (this.callBack) {
                    this.callBack(false, "没有完成播放")
                    this.callBack = null;
                }
            }
        })

        this.adVideoAd.onError(err => {
            console.log("AdVieo" + err)
        });
    }

    InitDataBase() {
        wx.cloud.init()
        this.database = wx.cloud.database();
    }

    ShowIniterstitalAd() {
        if (!this.adInterstitial) {
            AppControll.IsShowInitInterstitial = false;
        }
        this.adInterstitial.show().catch((err) => {
            console.error(err)
        })
    }

    ShowRewardVideoAd(target: any, callBack: (bool: boolean, str: string) => void) {
        super.ShowRewardVideoAd(target, callBack);
        if (AppControll.isDebug) return;
        if (sys.platform != sys.Platform.WECHAT_GAME) {
            console.log("当前环境不是微信小程序")
            return;
        }
        if (!this.adVideoAd) return;
        if (!this.callBack) this.callBack = callBack;
        this.adVideoAd.show().catch(error => {
            if (this.callBack) {
                this.callBack(false, "拉取广告失败");
                this.callBack = null;
            }
        });
    }

    PostMessage(data: any): void {
        if (sys.platform != sys.Platform.WECHAT_GAME) {
            console.log("当前环境不是微信小程序")
            return;
        }
        wx.postMessage(data);
    }


    InitShare() {
        wx.showShareMenu();
        //分享回调
        wx.onShareAppMessage(function () {
            let arr = [
                {
                    imageUrlId: "ZRkFZG6BRvmxTWSLYZvhRw==",
                    imageUrl: "https://mmocgame.qpic.cn/wechatgame/dpNWPb3e5y5t8eACTJRG9lAHUYcjIiaibLS3eia0eZpvCRLK6hiaE4svHx19Fn9Oj1kT/0"
                }
            ]
            return arr[0];
        })
    }

    Share(success?, fail?): void {
        let arr = [
            "https://mmocgame.qpic.cn/wechatgame/dpNWPb3e5y5t8eACTJRG9lAHUYcjIiaibLS3eia0eZpvCRLK6hiaE4svHx19Fn9Oj1kT/0",
        ]
        wx.shareAppMessage({
            title: "邀请你一起玩《炮塔指挥官》>>>",
            imageUrl: arr[0]
        });
    }

    CreateBanner(pos) {
        this.adBanner = wx.createBannerAd({
            adUnitId: this.strBannerId,
            adIntervals: 30,
            style: {
                left: pos.x,
                top: pos.y,
                width: pos.width,
                height: pos.height
            }
        })
        this.adBanner.onError(err => {
            console.log("ADBanner" + err)
        })
        if (this.adBanner) this.adBanner.show();
    }

    DestoryBanner(): void {
        if (!this.adBanner) return;
        this.adBanner.hide();
        this.adBanner.destroy()
    }

    CreateCustomAd(pos) {
        this.adCustom = wx.createCustomAd({
            adUnitId: this.strMateId,
            adIntervals: 30,
            style: {
                left: pos.x,
                top: pos.y,
                width: pos.width, // 用于设置组件宽度，只有部分模板才支持，如矩阵格子模板
                height: pos.height,
                fixed: false // fixed 只适用于小程序环境
            }
        })
        this.adCustom.show()
    }

    DestoryCustom() {
        if (!this.adCustom) return;
        this.adCustom.hide();
        this.adCustom.destroy()
    }

    UpdateRank() {
        if (!this.userInfo) {
            this.userInfo = {
                nickName: DataHelper.GetConfigByKey(ConfigKey.defaultUserName).value,
                avatarUrl: ""
            }
            GameData.userInfo = this.userInfo;
        };
        wx.cloud.callFunction({
            name: "updateRank",
            data: {
                honor: GameData.playerData.Honor,
                nickName: this.userInfo.nickName,
                headImg: this.userInfo.avatarUrl,
            }
        })

        // if (GameData.openId == "olums4v6vIG91JxR04esc-i_XN9c") {
        //     GameData.playerData.MGAutomaticAttackLv = 5;
        //     if (GameData.playerData.UnLockSecondaryGun.indexOf(400002) == -1) {
        //         GameData.UnlockdaryGun(400002);
        //         let temp: SecondaryGunStruct = {
        //             configId: 400015,
        //             level: 1
        //         }
        //         GameData.SetSecondaryGunByUnlockId(400002, temp);
        //     }
        //     if (GameData.playerData.skin.indexOf(110006) == -1) {
        //         GameData.playerData.skin.push(110006);
        //     }
        //     if (GameData.playerData.skin.indexOf(110002) == -1) {
        //         GameData.playerData.skin.push(110002);
        //     }
        //     if (GameData.playerData.skin.indexOf(110007) == -1) {
        //         GameData.playerData.skin.push(110007);
        //     }
        //     if (GameData.playerData.skin.indexOf(110005) == -1) {
        //         GameData.playerData.skin.push(110005);
        //     }
        //     if (GameData.playerData.skin.indexOf(110003) == -1) {
        //         GameData.playerData.skin.push(110003);
        //     }
        //     if (GameData.playerData.skin.indexOf(110004) == -1) {
        //         GameData.playerData.skin.push(110004);
        //     }

        //     EvtManger.do(EventName.automaticUpgrade);
        //     EvtManger.do(EventName.secondGuide);
        // }
    }

    UpdateLevelR(level: number, time: number) {
        if (!this.userInfo) {
            this.userInfo = {
                nickName: DataHelper.GetConfigByKey(ConfigKey.defaultUserName).value,
                avatarUrl: ""
            }
            GameData.userInfo = this.userInfo;
        };
        wx.cloud.callFunction({
            name: "updateLevelR",
            data: {
                level: level,
                time: time,
                nickName: this.userInfo.nickName,
                headImg: this.userInfo.avatarUrl,
            }
        })
    }

    GetLevelRank(callback: (res) => void) {
        super.GetLevelRank(callback);
        wx.cloud.callFunction({
            name: "getLevelRank",
        }).then(res => {
            callback(res.result.data);
        })
    }

    GetRankList(callback: (res) => void): any {
        super.GetRankList(callback);
        wx.cloud.callFunction({
            name: "getRankList",
        }).then(res => {
            callback(res.result.data);
        })
    }

    GetMyLevelR(callback: (res) => void) {
        wx.cloud.callFunction({
            name: "getMyLevelR",
        }).then(res => {
            if (res.result.data.length > 0) {
                callback(res.result.data[0]);
            } else {
                callback(null)
            }

        })
    }

    GetOpenId() {
        wx.cloud.callFunction({
            name: "getOpenid",
        }).then(res => {
            GameData.openId = res.result;
        })
    }

    SendBuryPoint(id: number): void {
        wx.cloud.callFunction({
            name: "buryPoint",
            data: {
                pointId: id,
            }
        })
    }

    ReoprtScene(id: number) {
        wx.reportScene({
            sceneId: id,
        })
    }

    JumpToforum() {

    }

    CreaterClubBtn(pos) {
        this.clubBtn = wx.createGameClubButton({
            icon: 'white',
            type: 'image',
            style: {
                left: pos.x,
                top: pos.y - 3,
                width: pos.width, // 用于设置组件宽度，只有部分模板才支持，如矩阵格子模板
                height: pos.height,
                fixed: false // fixed 只适用于小程序环境
            },
        })
    }

    ShowClubBtn(): void {
        if (this.clubBtn) {
            this.clubBtn.show();
        }
    }

    HideClubBtn(): void {
        if (this.clubBtn) {
            this.clubBtn.hide();
        }
    }

}
declare let wx: any;



